<template>
    <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
        <!-- 职工代表大会编辑 -->
        <a-form-model
            ref="ruleForm"
            :model="form"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            :rules="editModel != 0 ? rules : {}"
        >
            <a-spin :spinning="loading">
                <!-- 表格 -->
                <a-card :bordered="false">
                    <title-name title="日常资料管理"></title-name>
                    <custom-form
                        :isEmit="false"
                        :formList="formList"
                        :form="form"
                        :editModel="editModel == 0 ? '' : ''"
                        @selectOrg="selectOrg"
                        @getProjectInfo="getProjectInfo"
                    >
                    </custom-form>
                </a-card>

                <a-card :bordered="false" v-if="dataSource&&dataSource.length&&!$route.query.isSign&&editModel==0">
                    <title-name title="签收信息"></title-name>
                    <custom-form
                            :isEmit="false"
                            :formList="formList2"
                            :form="form2"
                            :editModel="editModel == 0 ? '' : ''"
                    >
                    </custom-form>
                    <a-table :columns="columns" :data-source="dataSource" :pagination="false" rowKey="id" border>
                        <template slot="idx" slot-scope="text, record, index">
                            {{index+1}}
                        </template>
                        <template slot="receiveStatus" slot-scope="text,record,index">
                            {{text == 1 ? '是': '否'}}
                        </template>
                    </a-table>
                </a-card>
                <!-- 页脚操作栏 -->
                <div class="btn_box page-btn-right-top" v-if="editModel != 0 && !isConsultation">
                    <a-button
                        class="button_right"
                        v-if="form.status == 'REJECTED'"
                        type="primary"
                        :loading="loadingBtn.REJECTED"
                        @click="handleSubmit('REJECTED')"
                        >保存</a-button
                    >
                    <a-button
                        v-else
                        class="button_right"
                        type="primary"
                        :loading="loadingBtn.DRAFT"
                        @click="handleSubmit('DRAFT')"
                        >保存草稿</a-button
                    >
                    <a-button
                        class="button_right"
                        type="primary"
                        :loading="loadingBtn.SUBMITTED"
                        @click="handleSubmit('SUBMITTED')"
                        >提交</a-button
                    >
                    <a-button type="primary" @click="handleActiveClose">关闭</a-button>
                </div>
                <div class="btn_box page-btn-right-top" v-else-if="!isConsultation">
                    <a-button type="primary" @click="signMsg" style="margin-right: 10px" v-if="$route.query.isSign&&$route.query.todoStatus!=1" :loading="signLoading">签收</a-button>
                    <a-button  @click="handleActiveClose">关闭</a-button>
                </div>
            </a-spin>
        </a-form-model>
       <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
    </base-breadcrumb>
</template>

<script>
import { addList, editList, getDetails } from '@/api/technical/dailyDataManag'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectPersonModal from '@/components/SelectPersonModal'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import { agencyReceive, createAgencyList } from "@/api/technology"
import { finishBusinessTodo } from '@/api/commons.js'
export default {
    name: 'a' + Date.now(),
    extends: new BaseEditPage(),
    data() {
        return {
            form2: {
              factNum: 0,
              receiveNum: 0
            },
            dataSource: [],
            columns: [
              {
                title: '序号',
                scopedSlots: {
                  customRender: 'idx'
                },
                width: 80
              },
              {
                title: '签收人',
                dataIndex: 'receivePersonId'
              },
              {
                title: '是否签收',
                dataIndex: 'receiveStatus',
                scopedSlots: {
                  customRender: "receiveStatus"
                }
              }
            ],
            signLoading: false,
            loading: false, // 加载控件
            visible: false, //弹窗控件
            editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
            form: {
                technicalReviewYearlyPlans: [],
                projectDeptId: '',
                sendPersonName: '',
                receiveUnitName: '',
                sendUnitName: null,
                receivePersonName: '',
              curId: '', projectId: "", branchCompanyId: "",
              fileInfoList: []
            }, // 表单
            id: '',
            yearsOpen: false,
            projectName: '',
            loadingBtn: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },

            rules: {
                messageType: [{ required: true, message: '请选择' }],
                messageName: [{ required: true, message: '请输入' }],
                messageNumber: [{ required: true, message: '请输入' }],
                dataType: [{ required: true, message: '请选择' }],
                messageAbstract: [{ required: true, message: '请输入' }],
                sendUnitName: [{ required: true, message: '请输入', trigger: 'change' }],
                sendPersonName: [{ required: true, message: '请输入' }],
                receiveUnitName: [{ required: true, message: '请输入', trigger: 'change' }],
                receivePersonName: [{ required: true, message: '请输入' }],
                receiveTime: [{ required: true, message: '请选择' }],
                remarks: [{ required: true, message: '请输入' }],
                // fileInfoList: [{ required: true, message: '请选择' }]
            },

            init: false, // 初始化控件
            titles: ['日常资料管理查看', '日常资料管理编辑', '日常资料管理新增'],
           //获取流程配置值
            processConfig: null,
            //点击提交发送流程配置值
            setProcessConfig: null,
            businessId: null
        }
    },
    props: {
        // 是否作为审批详情
        isAudit: {
            type: Boolean,
            default: false
        },
        // 是否作为意见征询
        isConsultation: {
            type: Boolean,
            default: false
        }
    },
    watch: {
        isAudit: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.$nextTick(() => {
                        this.editModel = 0
                    })
                }
            }
        },
        'form.messageType'(e) {
            if (this.editModel != 0 && this.init) {
                this.$nextTick(() => {
                    if (this.form.messageType == 0) {
                        this.form.sendUnitName = this.form.projectName
                        this.form.receiveUnitName = null
                    } else {
                        this.form.receiveUnitName = this.form.projectName
                        this.form.sendUnitName = null
                    }
                    // this.$refs.ruleForm?.validateField('receiveUnitName')
                    // this.$refs.ruleForm?.validateField('sendUnitName')
                    this.form.receivePersonName = null
                    this.form.sendPersonName = null
                })
            }
        }
    },
   async mounted() {
        this.$route.meta.title = ['日常资料管理查看', '日常资料管理编辑', '日常资料管理新增'][this.editModel]
        // 不为添加时请求详情
        if (this.editModel != 2) {
            this.getDetails()
        } else {
            this.form.curId = this.$userInfo().currentPost.id
            this.$nextTick(() => {
                this.init = true
            })
        }
       //获取通过获取流程配置值
      this.processConfig = await this.$getConfigFn('technology_daily_data_management')
    },
    computed: {
      formList2() {
        let str = ''
        if(this.form.messageType == '0') {
          str = '抄送'
        } else {
          // 发文对应下发人
          str = '下发'
        }
        return [
          {
            keyName: 'receiveNum',
            type: 'a-input',
            label: `应${str}人数`,
            disabled: true,
          },
          {
            keyName: 'factNum',
            type: 'a-input',
            label: '实际签收人数',
            disabled: true,
          },
        ]
      },
        formList() {
            return [
              {
                label: '所属单位',
                type: 'orgTree',
                keyName: 'curId',
                rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
                span: 16,
                isAutoSelectFirst:true,
                isNeedAuth:true,
                checkStrictly: true,
                disabled:true,
                statusSet:[1,2,3,4,5,6],
                isQueryProjecDetail: true
              },
                // {
                //     type: SelectSubCompany,
                //     keyName: 'branchCompanyId',
                //     label: '分公司名称',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2
                //     }
                // },
                // {
                //     type: SelectProject,
                //     keyName: 'projectId',
                //     label: '项目名称',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2,
                //         keyValue: 'branchCompanyId',
                //         isClear: this.editModel == 2,
                //         isEdit: this.editModel != 2,
                //         form: this.form
                //     },
                //     selectChange: (e) => {
                //         console.log(e)
                //         this.$set(this.form, 'projectDeptId', e.projectDeptId)
                //         this.form.projectName = e?.name
                //     }
                // },
                {
                    keyName: 'messageType',
                    type: 'a-select',
                    label: '收发文类型',
                    disabled: this.editModel == 0,
                    data: [
                        {
                            label: '发文',
                            value: '0'
                        },
                        {
                            label: '收文',
                            value: '1'
                        }
                    ]
                },
                {
                    keyName: 'messageName',
                    type: 'BaseInput',
                    label: '文件名称',
                    disabled: this.editModel == 0
                },
                {
                    keyName: 'messageNumber',
                    type: 'BaseInput',
                    label: '文件编号',
                    disabled: this.editModel == 0
                },
                {
                    keyName: 'dataType',
                    type: 'a-select',
                    label: '资料类型',
                    disabled: this.editModel == 0,
                    data: [
                        {
                            label: '普通',
                            value: '0'
                        },
                        {
                            label: '重大',
                            value: '1'
                        }
                    ]
                },
                {
                    keyName: 'messageAbstract',
                    type: 'BaseTextarea',
                    label: '内容摘要',
                    disabled: this.editModel == 0,
                    span: 24
                },
                {
                    keyName: 'sendUnitName',
                    type: 'BaseInput',
                    label: '发文单位',
                    disabled: this.form.messageType == 0 || this.editModel == 0
                },
                {
                    keyName: 'sendPersonName',
                    type: 'BaseInput',
                    label: '发放人',
                    hidden: this.form.messageType != 1,
                    disabled: this.editModel == 0
                },
                {
                    keyName: 'sendPersonName',
                    type: SelectPersonByProject,
                    hidden: this.form.messageType != 0,
                    disabled: this.editModel == 0,
                    label: '发放人',
                    wrap: true,
                    attrs: {
                        isOrg: true,
                        showSearch: true,
                        orgId: this.form.projectDeptId
                    }
                },

                {
                    keyName: 'receiveUnitName',
                    type: 'BaseInput',
                    label: '签收单位',
                    disabled: this.form.messageType == 1 || this.editModel == 0
                },
                {
                    keyName: 'receivePersonName',
                    type: 'BaseInput',
                    label: '签收人',
                    hidden: this.form.messageType != 0,
                    disabled: this.editModel == 0
                },
                {
                    keyName: 'receivePersonName',
                    type: SelectPersonByProject,
                    hidden: this.form.messageType != 1,
                    disabled: this.editModel == 0,
                    label: '签收人',
                    attrs: {
                        isOrg: true,
                        showSearch: true,
                        orgId: this.form.projectDeptId
                    }
                },
                {
                    keyName: 'receiveTime',
                    type: 'a-date-picker',

                    disabled: this.editModel == 0,
                    label: '签收时间',
                    attrs: {
                        valueFormat: 'YYYY-MM-DD'
                    }
                },
                {
                    keyName: 'remarks',
                    type: 'BaseTextarea',
                    label: '备注',
                    disabled: this.editModel == 0,
                    span: 24
                },
                {
                    keyName: 'fileInfoList',
                    type: 'uploadFile',
                    label: '附件上传',
                    disabled: this.editModel == 0,
                    span: 24,
                    businessCode: 'FACE10'
                }
            ]
        }
    },
    methods: {
      createAgencyList() {
        const data = {
          managementId: this.$route.query.id
        }
        createAgencyList(data).then(res=>{
         this.dataSource = res.data.list || []
          this.form2 = res.data
        })
      },
      signMsg() {
        this.$confirm({
          title: '确认签收?',
          onOk:()=> {
            this.signLoading = true
            const params = {
              managementId: this.$route.query.id,
              receivePersonId: this.$userInfo().id
            }
            agencyReceive(params).then( async res=>{
             await finishBusinessTodo({id: this.$route.query.msgid})
              this.signLoading = false
              this.$message.success("签收成功")
              this.$router.back()
            }).catch(()=>{
              this.signLoading = false
            })
          },
          onCancel() {

          }
        });

      },
      selectOrg(val) {
        if(val.length&&val.length < 2) {
          this.form.branchCompanyId = val[val.length - 1].orgId
        } else if(val.length >= 2 ) {
          this.form.branchCompanyId = val[val.length - 2].orgId
          this.form.projectName = val[val.length - 1].projectName
          this.form.projectId = val[val.length - 1].projectId
        }
      },
      getProjectInfo(info) {
        this.$set(this.form, 'projectDeptId', info.projectDeptOrgId)
      },
        getDetails() {
            this.loading = true
            console.log(this.id)
            getDetails({ id: this.id })
                .then((res) => {
                    this.loading = false
                    this.form = res.data
                  if(this.form.projectId) {
                    this.form.curId =  this.form.projectId
                  } else {
                    this.form.curId =  this.form.branchCompanyId
                  }
                  // 发文对应抄送人
                  if(this.form.messageType == '0') {
                    this.columns[1].title = '抄送人'
                  } else {
                    // 发文对应下发人
                    this.columns[1].title = '下发人'
                  }
                    if(this.form.auditStatus == '3') {
                      this.createAgencyList()
                    }
                    this.$nextTick(() => {
                        this.init = true
                    })
                })
                .catch(() => {
                    this.loading = false
                })
        },
        /**
         * 提交表单
         */
        validateForm() {
            let flag = false
            console.log(this.$refs.ruleForm)
            this.$refs.ruleForm.validate((e) => {
                if (e) {
                    flag = true
                  if(!this.form.fileInfoList || !this.form.fileInfoList.length) {
                    flag = false
                    this.$message.warning("请上传附件")
                  }
                } else {
                  this.$message.warning("请填写完所有必填项信息")
                }

            })

            console.log(flag)
            return flag
        },
        okSubmit(status) {},
        /**
         * 提交表单
         */
        handleSubmit(status) {
            this.setProcessConfig = null;
            if (status == 'SUBMITTED' && !this.validateForm()) {
                return
            }
            this.loading = true
            this.loadingBtn[status] = true

            let form = this.$clone(this.form)
            if (status != 'REJECTED') {
                form.auditStatus = status == 'SUBMITTED' ? 1 : 0
            } else {
                form.auditStatus = 5
            }
            let api = [editList, addList][this.editModel - 1] // 根据操作切换url地址
          this.submitApprovalConfirm(status =='SUBMITTED' ? this.processConfig : 6, (flag)=>{
            if(!flag) {
              this.loading = false
              this.loadingBtn[status] = false
              return
            }
            api(form)
                .then((res) => {
                    this.loading = false
                    this.loadingBtn[status] = false
                    this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
                     if(status =='SUBMITTED') {
                        //提交时，返回id
                        this.businessId = res.data.id;
                        this.setProcessConfig = this.processConfig;
                        return
                        }else{
                        this.$multiTab.close()
                    }
                })
                .catch(() => {
                    this.loadingBtn[status] = false
                    this.loading = false
                    this.$message.warning(err.data.message)
                })

          })
        }
    }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
    .ant-input:not([disabled]),
    .ant-select:not(.ant-select-disabled) .ant-select-selection,
    .ant-calendar-picker-input,
    .ant-input-number:not([disabled]),
    .ant-cascader-picker {
        border-color: #e4ac0b;
        background-color: #fff9e8;
    }
    .ant-input-disabled,
    .ant-input-number-disabled .ant-input-number-input,
    .ant-time-picker-input[disabled] {
        border-color: #d9d9d9 !important;
        background-color: #f5f5f5 !important;
    }
    .remark {
        .ant-input {
            border-color: inherit;
            background-color: initial;
        }
    }
}
</style>
